package com.cy.pj.sys.controller;

import com.cy.pj.common.pojo.JsonResult;
import com.cy.pj.common.util.PageUtil;
import com.cy.pj.sys.pojo.SysUser;
import com.cy.pj.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/user/")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @GetMapping
    public JsonResult doFindUsers(SysUser sysUser){
        return new JsonResult(PageUtil.startPage().doSelectPageInfo(()->sysUserService.findUsers(sysUser)));
    }

    @GetMapping("{id}")
    public JsonResult doFindById(@PathVariable Integer id){
        return new JsonResult(sysUserService.findById(id));
    }

    @PostMapping
    public JsonResult doSaveUser(@RequestBody SysUser sysUser){
        sysUserService.saveUser(sysUser);
        return new JsonResult("save ok");
    }

    @PutMapping
    public JsonResult doUpdateUser(@RequestBody SysUser sysUser){
        sysUserService.updateUser(sysUser);
        return new JsonResult("update ok");
    }

    @RequiresPermissions("sys:user:update")
    @PatchMapping("{id}/{valid}/{modifiedUser}")
    public JsonResult doValidById(@PathVariable Integer id,@PathVariable Integer valid,@PathVariable String modifiedUser){
        sysUserService.validById(id, valid, modifiedUser);
        return new JsonResult("update ok");
    }

    @GetMapping("login/{username}/{password}")
    public JsonResult doLogin(@PathVariable String username,@PathVariable String password){

        //将用户传过来的账户和密码封装，并通过subject将其提交给securityManager
        AuthenticationToken token=new UsernamePasswordToken(username,password);
        Subject subject= SecurityUtils.getSubject();
        subject.login(token);

        return new JsonResult("login ok");
    }
}
